package gl.func.updoladPicture;

import gl.App;
import gl.BaseActivity;
import gl.android.biyiqing.R;
import gl.uitls.Lg;
import gl.uitls.Tip;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.edmodo.cropper.CropImageView;

import de.greenrobot.event.EventBus;

public class SelectPictureActivity extends BaseActivity implements
		OnClickListener {

	GridView gridGallery;
	Handler handler;
	CustomGalleryAdapter adapter;
	ArrayList<String> imagePaths;
	ImageView imgSinglePick;
	Button btnGalleryPick;
	Button btnGalleryPickMul;

	String action;
	ViewSwitcher viewSwitcher;

	private Button btn_take_photo, btn_cancel;
	private final String tempPicture = Environment
			.getExternalStorageDirectory() + "/" + ".tmpimg";
	private static String LastPicture = App.getApp().getFilesDir() + "/"
			+ System.currentTimeMillis() + ".lastimg";
	private int requestCode = 0;
	private String[] path;

	public static final int DefaultRequestCode = 0;
	// End Of Content View Elements
	public final static int REQUESTCODE_TAKE_AVATOR = 9527;
	public final static int REQUESTCODE_TAKE_ALBUM = 9528;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_picture);

		init();
		initCrop();
	}

	// Static final constants
	private static final int DEFAULT_ASPECT_RATIO_VALUES = 10;
	private static final int ROTATE_NINETY_DEGREES = 90;
	private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
	private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
	private CropImageView cropImageView;
	private View vg_crop;
	private boolean needCrop = false;

	private void initCrop() {
		vg_crop = findViewById(R.id.vg_crop);
		// Initialize components of the app
		cropImageView = (CropImageView) findViewById(R.id.CropImageView);
		// Sets initial aspect ratio to 10/10, for demonstration purposes
		cropImageView.setAspectRatio(27,
				33);
		cropImageView.setFixedAspectRatio(true);
		
		final Button cropButton = (Button) findViewById(R.id.Button_crop);
		cropButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Bitmap croppedImage;
				try {
					croppedImage = cropImageView.getCroppedImage();
				} catch (Exception e1) {
					e1.printStackTrace();
					Tip.show("裁剪失败");
					return;
				}

				File file = new File((String) cropImageView.getTag());
				FileOutputStream fOut;
				try {
					fOut = new FileOutputStream(file);
					if (file.exists()) {
						croppedImage.compress(Bitmap.CompressFormat.PNG, 85, fOut);
						fOut.flush();
						fOut.close();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				imgSinglePick.setImageBitmap(croppedImage);
				vg_crop.setVisibility(View.GONE);
			}
		});

	}

	private void init() {

		handler = new Handler();
		gridGallery = (GridView) findViewById(R.id.gridGallery);
		gridGallery.setFastScrollEnabled(true);
		adapter = new CustomGalleryAdapter(getApplicationContext());
		adapter.setMultiplePick(false);
		gridGallery.setAdapter(adapter);

		gridGallery
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView,
							View view, int i, long l) {
						Toast.makeText(SelectPictureActivity.this,
								"" + imagePaths.get(i), Toast.LENGTH_LONG)
								.show();
					}
				});

		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
		viewSwitcher.setDisplayedChild(1);

		imgSinglePick = (ImageView) findViewById(R.id.imgSinglePick);
		imgSinglePick.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (imagePaths != null)// if minimum image is choose
					Toast.makeText(SelectPictureActivity.this,
							"" + imagePaths.get(0), Toast.LENGTH_LONG).show();
			}
		});

		btnGalleryPick = (Button) findViewById(R.id.btnGalleryPick);
		btnGalleryPick.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent i = new Intent(Action.ACTION_PICK);
				startActivityForResult(i, 100);

			}
		});

		btnGalleryPickMul = (Button) findViewById(R.id.btnGalleryPickMul);
		btnGalleryPickMul.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Manifest recognize our multiple request by this way
				Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
				startActivityForResult(i, 200);
			}
		});

		btn_take_photo = (Button) this.findViewById(R.id.btn_take_photo);
		// btn_pick_photo = (Button) this.findViewById(R.id.btn_pick_photo);
		btn_cancel = (Button) this.findViewById(R.id.btn_cancel);
		requestCode = getIntent()
				.getIntExtra("requestCode", DefaultRequestCode);
		if (requestCode == REQUESTCODE_TAKE_AVATOR) {
			needCrop = true;
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					final Animation loadAnimation = AnimationUtils
							.loadAnimation(getApplicationContext(),
									android.R.anim.fade_out);
					loadAnimation.setDuration(800);
					btnGalleryPickMul.setVisibility(View.GONE);
					btnGalleryPickMul.startAnimation(loadAnimation);
				}
			}, 300);

		}
		btn_cancel.setOnClickListener(this);
		// btn_pick_photo.setOnClickListener(this);
		btn_take_photo.setOnClickListener(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		imagePaths = new ArrayList<String>();
		if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
			adapter.clear();

			viewSwitcher.setDisplayedChild(1);
			String single_path = data.getStringExtra("single_path");
			imagePaths.add(single_path);
			App.mFBitmap.display(imgSinglePick, "file://" + single_path);
			showCrop(single_path);
			if (!TextUtils.isEmpty(single_path)) {
				this.path = new String[] { single_path };
			}
			else {
				Tip.show("err when take a photo ");
			}

		}
		else if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
			String[] all_path = data.getStringArrayExtra("all_path");

			ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();

			for (String string : all_path) {
				CustomGallery item = new CustomGallery();
				item.sdcardPath = string;
				imagePaths.add(string);
				dataT.add(item);
			}
			viewSwitcher.setDisplayedChild(0);
			adapter.addAll(dataT);
			this.path = all_path;
		}
		if (resultCode == Activity.RESULT_OK && requestCode == RequestCodeTake) {
			// 将保存在本地的图片取出并缩小后显示在界面上
			Bitmap camorabitmap = BitmapFactory.decodeFile(tempPicture);
			Lg.i(this, camorabitmap == null);
			if (null != camorabitmap) {

				// 下面这两句是对图片按照一定的比例缩放，这样就可以完美地显示出来。
				@SuppressWarnings("deprecation")
				int scale = reckonThumbnail(
						camorabitmap.getWidth(),
						camorabitmap.getHeight(),
						((WindowManager) App.getApp().getSystemService(
								WINDOW_SERVICE)).getDefaultDisplay().getWidth(),
						((WindowManager) App.getApp().getSystemService(
								WINDOW_SERVICE)).getDefaultDisplay()
								.getHeight());
				Bitmap bitMap = PicZoom(camorabitmap, camorabitmap.getWidth()
						/ scale, camorabitmap.getHeight() / scale);

				// 将处理过的图片显示在界面上，并保存到本地
				// photoImgView.setVisibility(View.VISIBLE);
				// photoImgView.setImageBitmap(bitMap);
				String path = savaPhotoToLocal(bitMap);
				// 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
				camorabitmap.recycle();
				if (!TextUtils.isEmpty(path)) {
					this.path = new String[] { path };
					viewSwitcher.setDisplayedChild(1);
					imagePaths.add(path);
					App.mFBitmap.display(imgSinglePick, "file://" + path);
					showCrop(path);
				}
				else {
					Tip.show("err when take a photo ");
				}

			}
		}
		if (resultCode != Activity.RESULT_OK) {
			finish();
			return;
		}
		if (needCrop) {

		}
	}

	private void showCrop(String uri) {
		if (!needCrop) {
			return;
		}
		vg_crop.setVisibility(View.VISIBLE);
		cropImageView.setTag(uri);
		cropImageView.setImageBitmap(BitmapFactory.decodeFile(uri));

	}

	boolean isInit;

	@Override
	protected void onResume() {

		if (path != null) {
			btn_cancel.setText("完成");
			btn_cancel.setBackgroundColor(getResources().getColor(
					R.color.green_light));
		}
		else {
			btn_cancel.setText("取消");
			btn_cancel.setBackgroundColor(getResources().getColor(R.color.red));
		}
		if (isInit) {
			btn_cancel.startAnimation(AnimationUtils.loadAnimation(
					getBaseContext(), R.anim.vibrate));
		}
		isInit = true;
		super.onResume();
	}

	/**
	 * go to pick image
	 */
	public synchronized static void pickImage(Activity activity, int requestCode) {
		Intent intent = new Intent(activity, SelectPictureActivity.class);
		intent.putExtra("requestCode", requestCode);
		activity.startActivityForResult(intent, requestCode);
	}

	public synchronized static void pickImage(Activity activity,
			int requestCode, boolean isCrop) {
		Intent intent = new Intent(activity, SelectPictureActivity.class);
		intent.putExtra("requestCode", requestCode);
		intent.putExtra("isCrop", isCrop);
		activity.startActivityForResult(intent, requestCode);
	}

	// @Override
	// public boolean onTouchEvent(MotionEvent event) {
	// onBackPressed();
	// return true;
	// }

	final int RequestCodeTake = 1;
	final int RequestCodePick = 2;

	public void onClick(View v) {
		if (v.getId() == R.id.btn_take_photo) {
			try {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(tempPicture)));
				startActivityForResult(intent, RequestCodeTake);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		else if (v.getId() == R.id.btn_cancel) {
			if (path != null) {
				EventBus.getDefault().post(
						new TakePicSucess(this.requestCode, path));
			}
			onBackPressed();
		}

	}

	public static int reckonThumbnail(int oldWidth, int oldHeight,
			int newWidth, int newHeight) {
		if ((oldHeight > newHeight && oldWidth > newWidth)
				|| (oldHeight <= newHeight && oldWidth > newWidth)) {
			int be = (int) (oldWidth / (float) newWidth);
			if (be <= 1)
				be = 1;
			return be;
		}
		else if (oldHeight > newHeight && oldWidth <= newWidth) {
			int be = (int) (oldHeight / (float) newHeight);
			if (be <= 1)
				be = 1;
			return be;
		}
		return 1;
	}

	public static Bitmap PicZoom(Bitmap bmp, int width, int height) {
		int bmpWidth = bmp.getWidth();
		int bmpHeght = bmp.getHeight();
		Matrix matrix = new Matrix();
		matrix.postScale((float) width / bmpWidth, (float) height / bmpHeght);

		return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeght, matrix, true);
	}

	public static String savaPhotoToLocal(Bitmap btp) {
		LastPicture = App.getApp().getFilesDir() + "/"
				+ System.currentTimeMillis() + ".lastimg";
		File tempFile = new File(LastPicture);
		String filePath = tempFile.getAbsolutePath();
		try {
			// 将bitmap转为jpg文件保存
			FileOutputStream fileOut = new FileOutputStream(tempFile);
			btp.compress(CompressFormat.JPEG, 100, fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return filePath;
	}

	public static Bitmap getLastPickImage() {
		File file = new File(LastPicture);
		if (!file.exists()) {
			return null;
		}
		else {
			return BitmapFactory.decodeFile(file.getAbsolutePath());
		}
	}
}
